<template>
    <view class="page">
        <view class="page-head">
            <statusBar></statusBar> 
            <view style="display: grid; grid-template-columns: repeat(3, 1fr); align-items: center;">
                <image src="/static/images/logo.png" style="width: 138rpx;height: 40rpx;margin-left: 20rpx;"></image>
                <view></view>
                <view></view>
            </view>
        </view>
        <view class="head-polyfill" :style="{ height: statusBarHeight + 38 + 'px' }"></view>
        <view class="chat-page" :style="{ height: contentHeight + 'px' }" v-if="userInfo.id">

            <!-- 聊天消息区域（可滚动） -->
            <scroll-view class="chat-content" scroll-y :style="{ height: contentHeight + 'px' }"
                :scroll-into-view="lastMsgId" ref="messageItem" scroll-with-animation :scroll-top="scrollTop">
                <view class="scrolltop">
                    <view class="message-item" v-for="(msg, idx) in messages" :key="idx" :id="'msg-' + idx">
                        <view :class="{ 'ai-avatar': msg.type == 'ai'}" v-if="msg.type == 'ai'">
                            <image src="/static/images/RHWS logo.png"></image>
                        </view>
                        <view class="msg-bubble"
                            :class="{ 'ai-msg': msg.type == 'ai', 'user-msg': msg.type == 'user' }">
                            <text class="msg-text">{{ msg.content }}</text>
                        </view>-
                    </view>
                </view>
            </scroll-view>

            <!-- 底部输入区域（动态高度） -->
            <view class="input-bar" :style="{ height: inputBarHeight + 'px' }">
                <textarea class="input-box" v-model="inputText" auto-height placeholder="请输入消息"
                    :placeholder-style="'color: #999'" @input="onTextareaInput"  disabled />
                <button class="send-btn" @click="sendMessage" disabled  >发送</button>
            </view>
        </view>
        <!-- <view class="chat-page" v-else  style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);color: #fff;">
            <view style="display: flex;flex-direction: column;align-items: center;">
                <view>请登录后使用</view>
                <button style="background-color: #3f7dff;height: 90rpx;">去登录</button>
            </view>
        </view> -->
    </view>

</template>

<script>
    import {
        getUser
    } from "@/common/api/user.js";
    import {
        getai
    } from "@/common/api/aichat.js";
    import statusBar from "@/components/public/status-bar/status-bar";
    import {
        mapState,
        mapMutations,
        mapActions
    } from "vuex";
    const system = uni.getSystemInfoSync();
    let statusBarHeight = system.statusBarHeight;
    // #ifdef MP-WEIXIN
    let custom = uni.getMenuButtonBoundingClientRect();
    statusBarHeight = custom.top;
    // #endif
    export default {
        components: {
            statusBar
        },
        data() {
            return {
                statusBarHeight,
                messages: [{
                    type: 'ai',
                    content: '嗨！我是润滑卫士AI小助手，目前正在进行系统升级，为了给您带来更流畅的体验，升级期间暂时无法正常服务哦，敬请期待全新版本的到来呀！'
                }],
                inputText: '',
                headerHeight: 44, // 标题栏高度
                inputHeight: 50, // 输入栏高度（根据实际调整）
                maxInputHeight: 120,
                contentHeight: 0,
                lastMsgId: 'msg-0',
                isReplying: false,
                thinkingMsgIndex: -1,
                scrollTopDefault: 20,
                scrollTop: 0
            };
        },
        async mounted() {
            console.log(this.userInfo)
            uni.$emit("hideLoading");
            if (this.userInfo.id) {
                const {
                    windowHeight
                } = wx.getSystemInfoSync();
                this.containerHeight = windowHeight * 2 - 240;

                const sysInfo = uni.getSystemInfoSync();
                const safeInputHeight = (this.inputBarHeight !== null && this.inputBarHeight !== undefined) ? this
                    .inputBarHeight : 116;
                this.contentHeight = (sysInfo?.windowHeight || 0) - (this.headerHeight || 0) - safeInputHeight;
            } else {

                uni.navigateTo({
                    url: "/pages/login/index",
                });
            }
        },
        computed: {
            ...mapState("User", ["userInfo", "token", "permissions"]),
        },
        methods: {
            ...mapActions("User", ["getUserInfo"]),
            onTextareaInput(e) {
                // 获取 textarea 的实时高度（单位：px）
                const {
                    height
                } = e.detail;
                // 限制最大高度（避免过高）
                const newHeight = Math.min(height + 20, this.maxInputHeight); // +20 为内边距补偿
                // 更新输入栏高度
                this.inputBarHeight = newHeight;
            },


            sendMessage() {
                if (!this.inputText.trim()) return;

                // 发送用户消息
                this.messages.push({
                    type: 'user',
                    content: this.inputText
                });
                this.lastMsgId = `msg-${this.messages.length - 1}`;

                // 添加"思考中..."消息（带加载状态）
                this.thinkingMsgIndex = this.messages.length;
                this.messages.push({
                    type: 'ai',
                    content: '思考中...',
                    isThinking: true // 标记为临时思考状态
                });
                this.lastMsgId = `msg-${this.thinkingMsgIndex}`;
                this.isReplying = true;

                this.getaicontent();
            },

            getaicontent() {
                let _this = this;
                getai({
                    message: _this.inputText
                }).then((res) => {
                    const fullContent = res.data; // 实际接口返回的完整内容
                    const targetMsg = _this.messages[_this.thinkingMsgIndex];

                    // 清除"思考中"状态，初始化逐字显示
                    targetMsg.isThinking = false;
                    let currentIndex = 0;
                    const timer = setInterval(() => {
                        // 逐字拼接内容（支持换行）
                        targetMsg.content = fullContent.slice(0, currentIndex + 1);
                        _this.lastMsgId = `msg-${_this.thinkingMsgIndex}`; // 保持滚动
                        currentIndex++;

                        const query = uni.createSelectorQuery().in(_this);
                        query.select('.scrolltop').boundingClientRect(data => {
                            console.log(data)
                            _this.scrollTop = _this.scrollTopDefault + data.height
                        }).exec();
                        // 完成后清除定时器
                        if (currentIndex >= fullContent.length) {
                            clearInterval(timer);
                            _this.isReplying = false;
                        }
                    }, 25); // 每50ms显示一个字符（可调整）
                    // 清空输入框
                    _this.inputText = '';
                }).catch((err) => {
                    // 接口失败时更新为错误提示
                    _this.messages[_this.thinkingMsgIndex] = {
                        type: 'ai',
                        content: '抱歉，当前回复失败，请重试~'
                    };
                    _this.isReplying = false;
                });
            },


        },
    };
</script>

<style lang="stylus" scoped>
    @import '~@/common/stylus/mixins';
    @import '~@/common/stylus/variable';

    .page {
        position: relative;
        min-height: calc(100vh - var(--window-top));
        padding-bottom: 50rpx;
        background: linear-gradient(180deg, #0D1523 0%, #102945 100%);
    }

    .page {
        padding-bottom: 150rpx;
        min-height: 100vh;
        box-sizing: border-box;
        background: linear-gradient(180deg, #0D1523 0%, #102945 100%);
    }

    .page-head {
        position: fixed;
        width: 100%;
        line-height: 64rpx;
        left: 0;
        top: 0;
        z-index: 998;
        text-align: center;
        font-size: 36rpx;
        font-family: PingFangSC-Regular, PingFang SC;
        transition: all 0.3s;
        color: #fff;
        background: #252e43;
        box-shadow: 0px 0px 8rpx 0px rgba(0, 0, 0, 0.12);
        padding-bottom: 12rpx;
    }

    /* #ifdef H5 */
    .page-head {
        padding-top: 12rpx;
    }

    /* #endif */
    .head-polyfill {
        /* #ifdef H5 */
        margin-bottom: 12rpx;
        /* #endif */
    }

    .chat-page {
        display: flex;
        flex-direction: column;
    }

    .chat-content {
        flex: 1;
        padding: 30rpx 0;
        background: #f8f8f8;
        overflow-y: auto;
    }

    .message-item {
        margin: 20rpx 0;
        display: flex !important;
        align-items: flex-start;
    }

    .ai-msg {
        background: #eaeaea;
        max-width: 80%;
        font-size: 28rpx;
        margin-right: auto;
    }

    .user-msg {
        background: #007aff;
        color: #fff;
        max-width: 80%;
        font-size: 28rpx;
        margin-left: auto;
        margin-right: 10rpx
    }

    .msg-bubble {
        padding: 16rpx 24rpx;
        border-radius: 16rpx;
        line-height: 1.4;
    }

    /* 关键修改：添加文本换行样式 */
    .msg-text {
        word-break: break-all;
        /* 强制所有字符换行（包括数字/字母） */
        white-space: pre-wrap;
        /* 保留换行符（如 \n） */
    }

    .input-bar {
        background: #fff;
        border-top: 2rpx solid #eee;
        display: flex;
        align-items: center;
        padding: 20rpx 30rpx;
        box-sizing: border-box;
        /* 关键：避免内边距撑开高度 */
    }

    .input-box {
        flex: 1;
        min-height: 72rpx;
        /* 初始高度 */
        padding: 16rpx 24rpx;
        border: 2rpx solid #eee;
        border-radius: 40rpx;
        font-size: 28rpx;
        line-height: 1.4;
        background: #fff;
        box-sizing: border-box;
        /* 关键：内边距不影响实际高度 */
    }

    .send-btn {
        width: 160rpx;
        height: 72rpx;
        margin-left: 20rpx;
        background: #007aff;
        color: #fff;
        border-radius: 40rpx;
        font-size: 28rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        flex-shrink: 0;
        /* 防止按钮被压缩 */
    }

    .ai-avatar {
        margin-left: 5rpx;
        margin-right: 10rpx;
        background: #007aff;
        color: #fff;
        width: 50rpx;
        height: 50rpx;
        border-radius: 50%;
    }

    .user-avatar {
        margin-left: 10rpx;
        margin-right: 5rpx;
        background: #007aff;
        color: #fff;
        width: 50rpx;
        height: 50rpx;
        border-radius: 50%;
    }

    .user-avatar image {
        width: 50rpx;
        height: 50rpx;
        border-radius: 50%;
    }

    .ai-avatar image {
        width: 50rpx;
        height: 50rpx;
        border-radius: 50%;
    }

    /* 新增思考中样式（带动态省略号） */
    .msg-bubble[isThinking]::after {
        content: '';
        animation: thinking 1.5s infinite;
        margin-left: 4rpx;
    }

    @keyframes thinking {
        0% {
            content: '.';
        }

        33% {
            content: '..';
        }

        66% {
            content: '...';
        }

        100% {
            content: '.';
        }
    }
</style>